package com.google.ar.sceneform.samples.hellosceneform.hosh.model

import android.view.animation.LinearInterpolator
import android.animation.ObjectAnimator
import com.google.ar.sceneform.math.QuaternionEvaluator
import com.google.ar.sceneform.math.Vector3
import com.google.ar.sceneform.math.Quaternion
import com.google.ar.sceneform.Node

/**
 * 旋转节点的实现参照了 https://www.jianshu.com/p/f058bf833af6
 */
class RotatingNode : Node() {
    var rotationAnimation: ObjectAnimator? = null
    var degreesPerSecond = 5.0f
    val speedMultiplier = 1.0f
    val animationDuration = (1000 * 360 / (degreesPerSecond * speedMultiplier)).toLong()

    // 启动动画
    fun startAnimation() {
        if (rotationAnimation != null) {
            return
        }

        rotationAnimation = createAnimator()
        rotationAnimation!!.target = this
        rotationAnimation!!.duration = animationDuration
        rotationAnimation!!.start()
    }

    // 停止动画
    fun stopAnimation() {
        if (rotationAnimation == null) {
            return
        }

        rotationAnimation!!.cancel()
        rotationAnimation = null
    }

    // 返回一个 ObjectAnimator 用来使节点旋转起来
    private fun createAnimator(): ObjectAnimator {
        // 节点的位置和角度信息设置通过Quaternion来设置
        // 创建4个Quaternion 来设置四个关键位置
        val orientation1 = Quaternion.axisAngle(Vector3(0.0f, 1.0f, 0.0f), 0f)
        val orientation2 = Quaternion.axisAngle(Vector3(0.0f, 1.0f, 0.0f), 120f)
        val orientation3 = Quaternion.axisAngle(Vector3(0.0f, 1.0f, 0.0f), 240f)
        val orientation4 = Quaternion.axisAngle(Vector3(0.0f, 1.0f, 0.0f), 360f)
        val rotationAnimation = ObjectAnimator()
        rotationAnimation.setObjectValues(orientation1, orientation2, orientation3, orientation4)
        // 设置属性动画修改的属性为 localRotation
        rotationAnimation.setPropertyName("localRotation")
        // 使用Sceneform 框架提供的估值器 QuaternionEvaluator 作为属性动画估值器
        rotationAnimation.setEvaluator(QuaternionEvaluator())
        //  设置动画重复无限次播放。
        rotationAnimation.repeatCount = ObjectAnimator.INFINITE
        rotationAnimation.repeatMode = ObjectAnimator.RESTART
        rotationAnimation.interpolator = LinearInterpolator()
        rotationAnimation.setAutoCancel(true)
        return rotationAnimation
    }

}